﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Security.Cryptography;

namespace KBLPrint
{
    public class ApiClient
    {
        private readonly HttpClient _httpClient;

        public ApiClient(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<string> PostJsonAsync<T>(string url, T payload, string secret)
        {
            var jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            string jsonStr = jsonContent + secret;
            // 添加签名逻辑
            var signature = GenerateMD5(jsonStr, System.Text.Encoding.UTF8); // 实现签名算法
            _httpClient.DefaultRequestHeaders.Add("Sign", signature);


            var response = await _httpClient.PostAsync(url, content);
            response.EnsureSuccessStatusCode();

            return await response.Content.ReadAsStringAsync();
        }

        public async Task<string> PostJsonAsync<T>(string url, T payload)
        {
            var jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync(url, content);
            response.EnsureSuccessStatusCode();

            return await response.Content.ReadAsStringAsync();
        }

        public string GenerateMD5(string txt, Encoding encoding = null)
        {
            if (encoding == null) encoding = Encoding.Default;
            using (MD5 mi = MD5.Create())
            {
                byte[] buffer = encoding.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }
    }
}
